package com.atguigu.myssm.filters;

import com.atguigu.utils.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @ClassName: CharacterEncodingFilter
 * @Description:
 * @Author: wty
 * @Date: 2022/12/8
 */
@WebFilter(urlPatterns = {"*.do"}, initParams = {@WebInitParam(name = "characterEncoding", value = "UTF-8")})
public class CharacterEncodingFilter implements Filter {
    private String characterEncoding = "UTF-8";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String characterEncodingStr = filterConfig.getInitParameter("characterEncoding");
        if (StringUtils.isNotEmpty(characterEncodingStr)) {
            characterEncoding = characterEncodingStr;
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 强转
        ((HttpServletRequest) servletRequest).setCharacterEncoding(characterEncoding);
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
